package com.example.admin.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.admin.model.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class RedisMessageListener implements MessageListener {

    private static final Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);

    int num = 0;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object value = stringRedisTemplate.getValueSerializer().deserialize(messageBody);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = stringRedisTemplate.getStringSerializer().deserialize(channelByte);
        logger.info("TOPIC: {}: VALUE: {} 计数器：{}", channel, value, num++);
        Map<String, Object> map =  JSON.parseObject(value.toString(), new TypeReference<Map<String, Object>>(){});
        logger.info("MAP: {}", map);
        Student student = JSON.toJavaObject(JSON.parseObject(map.get("202307120004").toString()), Student.class);
        logger.info("PERSON: {}", student);
        for (String key : map.keySet()) {
            logger.info("KEY: {} VALUE: {}", key, JSON.toJavaObject(JSON.parseObject(map.get(key).toString()), Student.class));
            logger.info("SEX: {} AGE: {}", JSON.toJavaObject(JSON.parseObject(map.get(key).toString()), Student.class).getSexName(), JSON.toJavaObject(JSON.parseObject(map.get(key).toString()), Student.class).getAge());
            Student student1 = new Student();
            BeanUtils.copyProperties(JSON.toJavaObject(JSON.parseObject(map.get(key).toString()), Student.class), student1);
            logger.info("student1: {}", student1);
        }
    }
}
